%%%-------------------------------------------------------------------
%%% @author mirahs(2892727493@qq.com)
%%% @doc
%%%     日期和时间相关工具
%%% @end
%%%-------------------------------------------------------------------
-module(util_time).

-export([
    get_now/0
    , millisecond/0
    ,unixtime/0
    ,datetime/0
    ,datetime_string/0
]).


%%%===================================================================
%%% API
%%%===================================================================

get_now() -> os:timestamp().

%% 获取当前的unix时间戳，精确到毫秒
millisecond() ->
    {MegaSecs, Secs, MicroSecs} = get_now(),
    erlang:trunc(MegaSecs * 1000000000 + Secs * 1000 + MicroSecs / 1000).

%% 获取当前的unix时间戳
unixtime() ->
    {MegaSecs, Secs, _MicroSecs} = get_now(),
    MegaSecs * 1000000 + Secs.

%% 获取当前日期时间
%% {{year(), month(), day()}, {hour(), minute(), seconds()}}
datetime() ->
    seconds_to_datetime(unixtime()).

%% 获取当前日期时间 <<"year-month-day hour:minute:seconds">>
datetime_string() ->
    {{Y,M,D}, {H,I,S}} = datetime(),
    util_io:fbin("~B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B", [Y,M,D,H,I,S]).


%% 将unix时间戳转换成当地日期时间 ->{{Y, M, D}, {h, m, s}}
seconds_to_datetime(Unixtime) ->
    Local = erlang:universaltime_to_localtime({{1970, 1, 1}, {0, 0, 0}}),
    LocalStamp = calendar:datetime_to_gregorian_seconds(Local),
    TimeStamp = Unixtime + LocalStamp,
    calendar:gregorian_seconds_to_datetime(TimeStamp).
